package com.zzyl.job;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

@Component
public class AlertRuleScheduledTasks {

    @Autowired
    private AlertRuleService alertRuleService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Scheduled(cron = "0 * * * * ?")
    public void alertRuleScheduledTasks() {
        //查询所有报警规则,判断是否为空，为空直接结束程序
        List<AlertRule> alertRuleList = alertRuleService.showAlertRule(null, null, null);
        if (ObjectUtil.isEmpty(alertRuleList)) {
            return;
        }

        //从redis中查询最新上报的数据,判断是否为空，为空直接结束程序
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_DATA);
        if (ObjectUtil.isEmpty(values)) {
            return;
        }

        //遍历最新上报的数据以每条的形式封装到新集合中
        List<DeviceDataVo> deviceDataVos = new ArrayList<>();
        values.forEach(v -> {
            deviceDataVos.addAll(JSONUtil.toList(v.toString(), DeviceDataVo.class));
        });

        //遍历每条数据进行报警规则比较
        deviceDataVos.forEach(deviceDataVo -> alertRuleService.alertFilter(deviceDataVo));
    }
}
